
from app.core.config import settings,TORTOISE_ORM
from app.models import get_tortoise_models
import copy
## shuju 数据库表模型 
models = get_tortoise_models()
TORTOISE_ORM = copy.deepcopy(TORTOISE_ORM)
TORTOISE_ORM['apps']['models']['models'] = models  # 修改拷贝

"""
带表名打印的数据库初始化脚本 ..数据表自己写
"""
## 添加数据表从 models下的init 添加 get_tortoise_models 这里
from datetime import datetime
from tortoise import Tortoise
from app.core.config import settings
from app.utils.app_log import logger
from app.models.base.user import User
from app.utils.user import get_password_hash


class DatabaseInitializer:
    """数据库初始化器"""
    async def init_database(self):
        """初始化数据库连接和表结构"""
        logger.info("初始化数据库...")
        model_configs = models.copy()
        try:
            # 确保包含aerich模型
            if "aerich.models" not in model_configs:
                model_configs.append("aerich.models")
            
            # 初始化 Tortoise ORM  .配置写到一起
            await Tortoise.init(config = TORTOISE_ORM)
            # logger.info("数据库连接初始化完成")

            # 创建表结构
            await Tortoise.generate_schemas()
            logger.info("数据库表创建完成")
            
            ## 自己看的时候打印一下
            # await self._print_created_tables()
            return True
        except Exception as e:
            logger.warning(f"初始化数据库错误: {e}")
            return False

    async def _print_created_tables(self):
        """打印已创建的数据表"""
        try:
            # 获取所有注册的模型
            created_tables = []
            # 遍历所有应用中的模型
            for app_name, models in Tortoise.apps.items():

                for model_name, model_class in models.items():
                    if hasattr(model_class._meta, 'db_table'):
                        table_name = model_class._meta.db_table
                        created_tables.append(table_name)
            
            # 去重并排序
            created_tables = sorted(list(set(created_tables)))
            logger.info(f"共创建 {len(created_tables)} 个数据表:")
            for i, table_name in enumerate(created_tables, 1):
                logger.info(f"  {i:2d}. {table_name}")

        except Exception as e:
            logger.warning(f"无法获取表信息: {e}")
 
    

    async def init_base_data(self):
        """初始化基础数据"""
        # logger.info("初始化基础数据...")
        try:
            # 系统配置
            if settings.enable_database:
                await self._init_system_config()
            # 管理员用户
            if settings.enable_user_system:
                await self._init_admin_user()
                
            # logger.info("基础数据初始化完成")
        except Exception as e:
            logger.error(f"⚠️ 基础数据初始化失败: {e}")
    

    async def _init_system_config(self):
        """初始化系统配置"""
        try:
            from app.models.base.system import SystemConfig
            default_configs = [
                {"key": "system_name", "value": "家庭功能系统", "description": "系统名称"},
                {"key": "system_version", "value": "1.0.0", "description": "系统版本"},
                {"key": "max_family_members", "value": "20", "description": "家庭最大成员数"},
            ]
            
            created_count = 0
            for config_data in default_configs:
                _, created = await SystemConfig.get_or_create(
                    key=config_data["key"],
                    defaults={
                        "value": config_data["value"],
                        "description": config_data["description"]
                    }
                )
                if created:
                    created_count += 1
                    
            # logger.info(f"系统配置初始化完成 ({created_count}项新配置)")
        except Exception as e:
            logger.warning(f" 系统配置初始化失败: {e}")
    

    async def _init_admin_user(self):
        """初始化管理员用户"""
        try:
            hashed_password = get_password_hash(password="admin123")

            admin_user, created = await User.get_or_create(
                username="admin",
                defaults={
                    "email": "admin@qq.com",
                    "password": hashed_password,
                    "full_name": "系统管理员",
                    "is_superuser": True,
                    "is_active": True
                }
            )
            
            # if created:
            #     logger.info("管理员用户创建完成")
            # else:
            #     logger.info("管理员用户已存在")
                
        except Exception as e:
            logger.warning(f"管理员用户初始化失败: {e}")
    

    async def close_database(self):
        """关闭数据库连接"""
        await Tortoise.close_connections()
        logger.info("数据库连接已关闭")
    
    async def run(self):
        """运行完整的初始化流程"""
        start_time = datetime.now()
        logger.info("开始数据库初始化...")
        
        try:
            await self.init_database()

            if settings.enable_auto_init_data:
                await self.init_base_data()
            else:
                logger.info("自动初始化数据已禁用")
            
            duration = (datetime.now() - start_time).total_seconds()
            logger.info(f"数据库初始化完成! 耗时: {duration:.2f}秒")
            
            if settings.enable_user_system:
                logger.info("默认账户: admin / admin123")
                
        except Exception as e:
            logger.error(f"数据库初始化失败: {e}")
            raise
        finally:
            await self.close_database()


initializer = DatabaseInitializer()